<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="候选人姓名" prop="cdName">
        <el-input v-model="queryParams.cdName" placeholder="请输入候选人姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证号" prop="idNumber" width="180">
        <el-input v-model="queryParams.idNumber" placeholder="请输入身份证号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="套餐类型" prop="packageType">
        <el-select v-model="queryParams.packageType" placeholder="全部" clearable>
          <el-option v-for="item in SetMealTypelist" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="背调编号" prop="number">
        <el-input v-model="queryParams.number" placeholder="请输入背调编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="操作人" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="全部">
          <el-option
            v-for="item in peoplelist"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="全部">
          <el-option
            v-for="item in optionsStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <!-- 0未开始 1调查中  2已完成  3异常 -->
      </el-form-item>
      <el-form-item label="报告结果" prop="orderOutcome">
        <!-- 1待出具2无风险3低风险4中风险5高风险 -->
        <el-select v-model="queryParams.orderOutcome" placeholder="全部" clearable>
          <el-option v-for="dict in dict.type.sys_report_result" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="daterangeCreateTime">
        <el-date-picker style="width: 210px" v-model="daterangeCreateTime" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
    </el-form>
    <div style="display: flex; justify-content: flex-end">
      <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">查询</el-button>
      <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
    </div>
    <el-divider></el-divider>
    <div class="header-box">
      <div class="button-right" style="margin-bottom: 15px">
        <el-button type="primary" icon="el-icon-download" size="small" @click="handleExport">导出Excel</el-button>
        <el-button type="primary" icon="el-icon-download" size="small" @click="handleExportPDF">批量导出PDF</el-button>
      </div>
    </div>

    <el-table v-loading="loading" ref="multipleTable" :data="reportDetailsList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"> </el-table-column><el-table-column type="index" label="序号"
        align="center" width="50">
      </el-table-column>
      <el-table-column label="候选人" align="center" prop="cdName" />
      <el-table-column label="身份证号" align="center" prop="idNumber" width="200" />
      <el-table-column label="个人信息" align="center" prop="perInfo" width="150">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ statusMap[scope.row.perInfo] || '未知状态' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="社会安全" align="center" prop="socialSecurity" width="200"><template slot-scope="scope">
          <span style="margin-left: 10px">
          {{ statusMap[Number(scope.row.socialSecurity)] || '未涉及查询' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="个人信用" align="center" prop="percredit" width="200"><template slot-scope="scope">
          <span style="margin-left: 10px">
            {{ statusMap[scope.row.perCredit] || '未涉及查询' }}
          </span>
        </template></el-table-column>
      <el-table-column label="商业利益冲突" align="center" prop="commercial" width="200"><template slot-scope="scope">
          <span style="margin-left: 10px">
            {{ statusMap[scope.row.commercial] || '未涉及查询' }}
          </span>
        </template></el-table-column>
      <el-table-column label="法院诉讼" align="center" prop="courtSue," width="200"><template slot-scope="scope">
          <span style="margin-left: 10px">
            {{ statusMap[scope.row.courtSue] || '未涉及查询' }}
          </span>
        </template></el-table-column>
      <el-table-column label="教育经历" align="center" prop="education" width="200"><template slot-scope="scope">
        <span style="margin-left: 10px">
          {{ statusMap[scope.row.education] || '未涉及查询' }}
        </span>
        </template></el-table-column>
      <el-table-column label="操作人" align="center" prop="username" width="200" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="操作" align="center" fixed="right" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看报告</el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleDown(scope.row)">下载报告</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleProgress(scope.row)">查看进度</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog title="查看报告" :visible.sync="dialogVisible" width="1000" :before-close="handleClose">
      <div style="display: flex;justify-content: flex-end;margin-bottom: 10px;margin-right: 20px;"><el-button
          type="primary" size="small" @click="handlePDF">下载pdf</el-button>
        <el-button type="primary" size="small" @click="handleWORD">下载word</el-button>
      </div>
      <iframe :src="htmlUrl" width="800px" height="500px"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import {
  listReportDetails,
  getReportDetails,
  delReportDetails,
  addReportDetails,
  updateReportDetails,
  getWord,
  getPDF
} from "@/api/report/reportDetails";
import { listMyUser} from "@/api/system/user";
import { downloadReport } from "@/api/order/order";

export default {
  name: "ReportDetails",
  dicts: ["sys_report_status", "sys_report_result"],
  data() {
    return {
      statusMap: {
        '-1': '未涉及查询',
        '1': '待出具',
        '2': '无风险',
        '3': '低风险',
        '4': '中风险',
        '5': '高风险'
      },
      peoplelist: [],
      optionsStatus: [{
        value: 3,
        label: '已出报告'
      }, {
        value: 4,
        label: '异常'
      }, {
        value: 5,
        label: '挂起'
      }],
      dialogVisible: false,
      SetMealTypelist: [
        {
          value: "0",
          label: "线上",
        },
        {
          value: "1",
          label: "线下",
        },
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报告列表表格数据
      reportDetailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门id时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        parentId: null,
        surveyId: null,
        surveyName: null,
        surveyStatus: null,
        surveyResult: null,
        reportUrl: null,
        createTime: null,
        userId: null,
        deptId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      multipleSelection: [],
      htmlUrl: "",
      pdfUrl: "",
      wordUrl: "",
    };
  },
  created() {
    this.getList();
    this.getPeoplelist();
  },
  methods: {
    // 拿到操作人列表
    getPeoplelist() {
      listMyUser().then(res => {
        this.peoplelist = res.data;
      })
    },
    /** 查询报告列表列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && "" != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] =
          this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listReportDetails(this.queryParams).then((response) => {
        this.reportDetailsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        parentId: null,
        surveyId: null,
        surveyName: null,
        surveyStatus: null,
        surveyResult: null,
        reportUrl: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        userId: null,
        deptId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报告列表";
    },
    /** 查看操作 */
    handleView(row) {
      const loading = this.$loading({
        lock: true,
        text: '正在加载，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      getWord({ id: 2 })
        .then((res) => {
          loading.close();
          this.dialogVisible = true;
          this.htmlUrl =
            process.env.VUE_APP_BASE_API + "profile/" + res.data.htmlUrl;
          this.pdfUrl = res.data.pdfUrl;
          this.wordUrl = res.data.wordUrl;
        })
        .catch((err) => { });
    },
    handlePDF() {
      window.open(this.pdfUrl, "_blank")
    },
    handleWORD() {
      window.open(this.wordUrl, "_blank")
    },
    handleClose() {
      this.dialogVisible = false;
      this.htmlUrl = "";
      this.pdfUrl = "";
      this.wordUrl = "";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateReportDetails(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReportDetails(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 下载按钮操作 */
    handleDown(row) {
      downloadReport({ orderId: row.id }).then((res) => {
        // let url = res.data;
        // const link = document.createElement('a');
        // link.href = url;
        // document.body.appendChild(link);
        // link.click();
        // document.body.removeChild(link);
        window.open(res.data)
      }).catch(err => {
        console.error('下载失败:', err);
      });
    },
    // /** 下载按钮操作 */
    // handleDown(row) {
    //   getWord({ id: row.id })
    //     .then((res) => {
    //       window.open(res.data.pdfUrl, "_blank")
    //     })
    //     .catch((err) => {
    //       console.error("下载失败:", err);
    //     });
    // },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "report/reportDetails/export",
        {
          ...this.queryParams,
        },
        `reportDetails_${new Date().getTime()}.xlsx`
      );
    },
    handleProgress(row) {
      this.$router.replace({
        path: "/reportDetails/ReportListProgressup",
        query: { info: row.id },
      });
    },
    // 导出pdf
    handleExportPDF() {
      this.download(
        "order/order/downloadBatchReport",
        {
          ...this.queryParams,
        },
        `reportDetails_${new Date().getTime()}.zip`
      );
    },
  },
};
</script>
